<template>
	<view>
		<view class="cu-item">
			<view class="cu-list menu-avatar comment">
				<text class="copy-comment" v-if="item.text!='['+$t('global.picture') +']'" @tap="ToCopy(item.text)">
					{{$t('global.copy')}}
				</text>
				<view class="cu-item">
					<view class="cu-avatar round" @tap="toUserContents(item.userJson)" :style="item.style"></view>
					<view class="content">
						<view class="text-grey">
						<block v-if="item.userJson.isvip>0">
							<block v-if="item.userJson.vip==1">
								<text class="text-red">
									{{item.userJson.name}}
								</text>
							</block>
							<block v-else>
								<text class="text-yellow">
									{{item.userJson.name}}
								</text>
							</block>
						</block>
						<block v-else>
							{{item.userJson.name}}
						</block>
						<block v-if="isHead">
							<image v-if="item.userJson.isvip>0" :src="vipImg" style="border-radius: 0px;margin-left: 6upx;margin-right: 0upx;width: 70upx;height: 35upx;" mode="widthFix"></image>
							<image :src="lvImg+getLv(item.userJson.experience)+'.png'" style="border-radius: 0px;margin-left: 6upx;margin-right: 0upx;width: 44upx;height: 22upx;" mode="widthFix"></image>
							<text class="userlv customize"
								style="border: 3upx solid black;color:black;padding: 2upx 10upx;border-radius: 40upx;background-color: transparent;"
								v-if="item.userJson.customize&&item.userJson.customize!=''">{{item.userJson.customize}}</text>
							</block>
						</view>
						
						<view class="text-content text-df break-all">
							<rich-text v-if="item.text!='['+$t('global.picture') +']'" :nodes="markHtml(item.text)"></rich-text>
							<view class="pic-box" v-if="itemPicArray.length">
								<template>
									<view v-if="itemPicArray.length === 1" class="single-pic">
										<u-image :src="itemPicArray[0]"
											@tap="previewImage(itemPicArray,itemPicArray[0])" width="400rpx"
											height="300rpx" :fade="true" duration="450" :lazy-load="true"
											border-radius="20">
											<u-loading slot="loading"></u-loading>
										</u-image>
									</view>
									<view v-else class="son-grid-pic"
										:style="{ gridTemplateColumns: 'repeat(3, 1fr)' }">
										<u-image v-for="(pic, index) in itemPicArray.slice(0, 9)" :key="index"
											:src="pic" @tap="previewImage(itemPicArray,itemPicArray[index])"
											width="170rpx" height="170rpx" :fade="true" duration="450" :lazy-load="true"
											border-radius="20">
											<u-loading slot="loading"></u-loading>
										</u-image>
									</view>
								</template>
							</view>
						</view>
						<view class="bg-cyan light padding-sm radius margin-top-sm  text-sm"
							style="border-radius: 20upx;" v-if="item.parent>0&&isContent">
							<view class="flex">
								<view class="flex-sub break-all">
									<view class="tn-flex">{{item.parentJson.username}}:
										<rich-text v-if="item.parentJson.text!='['+$t('global.picture') +']'" :nodes="markHtml(item.parentJson.text)"></rich-text></view>
									<view class="son-pic-box" v-if="parentPicArray.length">
										<view v-if="parentPicArray.length === 1" class="single-pic">
											<u-image :src="parentPicArray[0]"
												@tap="previewImage(parentPicArray,parentPicArray[0])" width="300rpx"
												height="200rpx" :fade="true" duration="450" :lazy-load="true"
												border-radius="20">
												<u-loading slot="loading"></u-loading>
											</u-image>
										</view>
						
										<view v-else class="son-grid-pic" :style="{ gridTemplateColumns: 'repeat(3, 1fr)' }">
											<u-image v-for="(pic, index) in parentPicArray.slice(0, 9)" :key="index"
												:src="pic" @tap="previewImage(parentPicArray,parentPicArray[index])"
												width="130rpx" height="130rpx" :fade="true" duration="450"
												:lazy-load="true" border-radius="17">
												<u-loading slot="loading"></u-loading>
											</u-image>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="bg-cyan light padding-sm radius margin-top-sm  text-sm"
							style="border-radius: 20upx;" v-if="!isContent">
							<view class="flex" @tap="toInfo(item.cid,item.contenTitle)">
								<view class="break-all">{{replaceSpecialChar(item.contenTitle)}}</view>
						
							</view>
						</view>
						<view class="margin-top-sm flex justify-between">
							<view class="text-gray text-df" style="font-size: 26upx;">{{formatDate(item.created)}}
							 <text class="margin-left-sm" v-if="$API.localOf()">{{getLocal(item.userJson.local)}}</text>
							</view>
							<view>
								<text class="tn-icon-praise" :class="item.isLikes==1?'text-cyan':''"  @tap="toLike(item.id),item.isLikes=1">
									<block v-if="item.likes>0">
										{{formatNumber(item.likes)}}
									</block>
								</text>
								<!-- #ifdef APP-PLUS || H5 -->
								<text class="tn-icon-comment margin-left-sm" @tap="handleTap(item.userJson.name,item.id)"></text>
								<!-- #endif -->
								<!-- #ifdef MP -->
								<text class="tn-icon-comment margin-left-sm" @tap="commentsAdd(item.userJson.name+':'+item.text,item.id,1,item.postJson.id)"></text>
								<!-- #endif -->
								
							</view>
						</view>
						<view class="comment-operation"  v-if="group=='administrator'||group=='editor'">
							<text class="text-black" @tap="toBan(item.userJson.uid)">{{$t('global.ban')}}</text>
							<text class="text-red" @tap="toDelete(item.id)">{{$t('common.delete')}}</text>
						</view>
					</view>
				</view>
				<u-divider :use-slot="false" half-width="40%"></u-divider>
							
				
			</view>
		</view>
	</view>
</template>

<script>
	import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	// #ifdef APP-PLUS
	import owo from '../../static/app-plus/owo/OwO.js'
	// #endif
	// #ifdef H5
	import owo from '../../static/h5/owo/OwO.js'
	// #endif
	// #ifdef MP
	var owo = [];
	// #endif
	export default {
		mixins: [darkModeMixin],
	    props: {
	        item: {
				type: Object,
				default: () => ({})
			},
			isHead: {
				type: Boolean,
				default: true
			},
			isContent: {
				type: Boolean,
				default: false
			}
	    },
		name: "commentItem",
		data() {
			return {
				owo:owo,
				vipImg: this.$API.SPvip(),
				lvImg: this.$API.SPLv(),
				owoList:[],
				group:""
			};
		},
		computed: {
			itemPicArray() {
				return this.item.pic ? this.item.pic.split('||') : [];
			},
			parentPicArray() {
				return (this.item.parentJson && this.item.parentJson.pic) ? this.item.parentJson.pic.split('||') : [];
			}
		},
		created(){
			var that = this;
			if(localStorage.getItem('userinfo')){
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.group = userInfo.group;
			}
			// #ifdef APP-PLUS || H5
			var owo = that.owo.data;
			var owoList=[];
			for(var i in owo){
				owoList = owoList.concat(owo[i].container);
			}
			that.owoList = owoList;
			// #endif
		},
		methods: {
			handleTap(author,coid) {
				this.$emit(
					'coAdd',
					'hf',
					author,
					coid,
				);
			},
			previewImage(imageList, image) {
				//预览图片
				uni.previewImage({
					urls: imageList,
					current: image
				});
			},
			subText(text,num){
				if(text.length < null){
					return text.substring(0,num)+"……"
				}else{
					return text;
				}
			},
			replaceSpecialChar(text) {
				text = text.replace(/&quot;/g, '"');
				text = text.replace(/&amp;/g, '&');
				text = text.replace(/&lt;/g, '<');
				text = text.replace(/&gt;/g, '>');
				text = text.replace(/&nbsp;/g, ' ');
				return text;
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				return result;
			},
			formatNumber(num) {
			    return num >= 1e3 && num < 1e4 ? (num / 1e3).toFixed(1) + 'k' : num >= 1e4 ? (num / 1e4).toFixed(1) + 'w' : num
			},
			goInfo(id){
				uni.navigateTo({
					url: '/pages/forum/info?id='+id
				});
			},
			goAds(data){
				var url = data.url;
				var type = data.urltype;
				// #ifdef APP-PLUS
				if(type==1){
					plus.runtime.openURL(url);
				}
				if(type==0){
					plus.runtime.openWeb(url);
				}
				// #endif
				// #ifdef H5
				window.open(url)
				// #endif
			},
			toUserContents(data){
				var that = this;
				var name = data.name;
				var title = data.name + that.$t('common.nameinfo');
				var id= data.uid;
				var type="user";
				uni.navigateTo({
				    url: '/pages/contents/userinfo?title='+title+"&name="+name+"&uid="+id+"&avatar="+encodeURIComponent(data.avatar)
				});
			},
			getUserLv(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var rankList = that.$API.GetRankList();
				return rankList[i];
			},
			getUserLvStyle(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var rankStyle = that.$API.GetRankStyle();
				var userlvStyle ="color:#fff;background-color: "+rankStyle[i];
				return userlvStyle;
			},
			getLv(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var lv  = that.$API.getLever(i);
				return lv;
			},
			getLvStyle(i){
				var that = this;
				if(!i){
					var i = 0;
				}
				var lv  = that.$API.getLever(i);
				var rankStyle = that.$API.GetRankStyle();
				var userlvStyle ="color:#fff;background-color: "+rankStyle[lv];
				return userlvStyle;
			},
			getLocal(local) {
				var that = this;
				if (local && local != '') {
					var local_arr = local.split("|");
					if (!local_arr[3] || local_arr[3] == 0) {
						return local_arr[2];
					} else {
						return local_arr[3];
					}
			
				} else {
					return that.$t('global.unknown')
				}
			
			},
			commentsAdd(title,coid,reply,postid){
				uni.navigateTo({
				    url: '/pages/forum/reply?postid='+postid+"&coid="+coid+"&title="+title+"&isreply="+reply
				});
			},
			markHtml(text){
				var that = this;
				text = that.replaceAll(text,"<","&lt;");
				text = that.replaceAll(text,">","&gt;");
				var owoList=that.owoList;
				for(var i in owoList){
					if(that.replaceSpecialChar(text).indexOf(owoList[i].data) != -1){
						text = that.replaceAll(that.replaceSpecialChar(text),owoList[i].data,"<img src='/"+owoList[i].icon+"' class='tImg' />")
					}
				}
				return text;
			},
			replaceAll(string, search, replace) {
			  return string.split(search).join(replace);
			},
			toBan(uid){
				var that = this;
				if(!uid){
					uni.showToast({
						title: that.$t('common.usernofound'),
						icon: 'none'
					})
					return false;
				}
				uni.navigateTo({
					url: '/pages/manage/banuser?uid='+uid
				});
			},
			toDelete(id){
				var that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					"id":id,
					"token":token
				}
				uni.showModal({
					title: that.$t('global.suredelcomment'),
					success: function (res) {
						if (res.confirm) {
							uni.showLoading({
								title: that.$t('common.loadmore')
							});
							that.$Net.request({
								url: that.$API.postCommentDelete(),
								data:data,
								header:{
									'Content-Type':'application/x-www-form-urlencoded'
								},
								method: "get",
								dataType: 'json',
								success: function(res) {
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
									uni.showToast({
										title: res.data.msg,
										icon: 'none'
									})
									that.$emit(
										'coDel'
									);
								},
								fail: function(res) {
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
									uni.showToast({
										title: that.$t('common.networkfail'),
										icon: 'none'
									})
								}
							})
						} else if (res.cancel) {
							
						}
					}
				});
			},
			ToCopy(text) {
				var that = this;
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({ //提示
							title: that.$t('common.copysuccess')
						})
					}
				});
				let textarea = document.createElement("textarea");
				textarea.value = text;
				textarea.readOnly = "readOnly";
				document.body.appendChild(textarea);
				textarea.select();
				textarea.setSelectionRange(0, text.length);
				uni.showToast({ //提示
					title: that.$t('common.copysuccess')
				})
				var result = document.execCommand("copy")
				textarea.remove();
			},
			toLike(id){
				var that = this;
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}else{
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return false;
				}
				if(that.item.isLikes==1){
					uni.showToast({
						title: that.$t('global.alreadyliked'),
						icon: 'none'
					});
					return false;
				}else{
					that.item.isLikes = 1;
				}
				var data = {
					token:token,
					id:id,
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.postCommentLike(),
					data:data,
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if(res.data.code==0){
							that.item.isLikes = 0;
						}else{
							that.item.likes += 1;
						}
					},
					fail: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
		}
	}
</script>

<style scoped>
	.single-pic u-image {
		width: 100%;
		height: auto;
	}

	.double-pic {
		display: flex;
		gap: 10rpx;
		justify-content: space-around;
	}

	.son-grid-pic {
		display: flex;
		gap: 10rpx;
		justify-items: center;
		flex-direction: row;
		flex-wrap: wrap;
	}

	.grid-pic {
		display: grid;
		gap: 10rpx;
	}

	.pic-box {
		margin: 20rpx 0;
	}

	.son-pic-box {
		margin: 15rpx 0;
	}

	.bg-cyan.light {
		color: #767676;
		background-color: #eeeeee;
		border-left: 10rpx solid #d5d5d5;
	}
	
	
</style>